﻿create procedure [mem].[kvGet]
(
	@Key varchar(255) not null,
	@TTL float null,
	@Version int out,
	@Expiry datetime2 out
) 
with NATIVE_COMPILATION, SCHEMABINDING, EXECUTE AS OWNER
as
begin atomic with (TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'us_english')

	declare @KeyId bigint
	select
		@KeyId = [KeyId],
		@Version = [Version],
		@Expiry = [Expiry]
	from mem.kv
	where [Key] = @Key 

	if @@rowcount = 0
	begin
		set @Version = -2147483648
		return;
	end

	if @TTL is not null
	begin
		set @Expiry = DATEADD(millisecond, @TTL, GETUTCDATE())
		update mem.kv set [Expiry] = @Expiry where [Key] = @Key
	end

	select LEN(Part), Part from mem.kvValues where [KeyId] = @KeyId order by [SortOrder]
end